package com.parmal.proxy.handler.http;

import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpForwardAndReceiveHandler extends ChannelHandlerAdapter{

    private Channel clientChannel;

    private Channel remoteChannel;

    private boolean closeNow = false;//是否断开与 remote、client的连接

    private static Logger logger = LoggerFactory.getLogger(HttpForwardAndReceiveHandler.class);

    public HttpForwardAndReceiveHandler(Channel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.remoteChannel = ctx.channel();
    }

    /**
     * 响应转发到客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("读到响应数据=>{}",msg.getClass());
        ChannelFuture channelFuture = this.clientChannel.writeAndFlush(msg);
        if(this.closeNow){//是否需要关闭
            this.remoteChannel.close();
            logger.info("断开与[{}]的连接",this.remoteChannel.remoteAddress());
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    /**
     * 请求转发到远程服务端
     * @param request 需要转发的请求
     * @return future
     */
    public ChannelFuture forwardRequest(FullHttpRequest request) {
        return this.remoteChannel.writeAndFlush(request);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("数据接受完成");
        this.clientChannel.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        this.remoteChannel.close();
        this.clientChannel.close();
    }



    /**
     * 在下一次响应结束后断开与remote和 client的连接
     */
    public void disconnectRemoteAndClient(){
        this.closeNow = true;
    }

}
